import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap, asyncRouterMap, constUrl } from './routes'
import {  Notification  } from 'element-ui'
import {getMenuByRouter} from './util'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth' 

NProgress.configure({ showSpinner: false })

Vue.use(Router)
const router = new Router({
  routes: constantRouterMap,
  // routes: constUrl,
  mode: 'hash'
})

const LOGIN_PAGE_NAME = 'login'

function hasOneOf(target, arr) {
  return target.some(_ => arr.indexOf(_) > -1
)
}

function hasAccess(role, route) {
  if (route.meta && route.meta.roles) {
    return hasOneOf(role, route.meta.roles)
  }
  return true
}


function canTurnTo(name, role, routes) {
  const routePermissionJudge = (list) =>
  {
    return list.some(item => {
      if(item.children && item.children.length
  )
    {
      return routePermissionJudge(item.children)
    }
  else
    if (item.name === name) {
      return hasAccess(role, item)
    }
  })
  }

  return routePermissionJudge(routes)
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = getToken()
  // if(!store.state.app.menus.length) {
  //   store.commit('ADD_MENUS',constUrl)
  //   next()
  // }else {
  //   next()
  // }
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    // 获取路由列表
    next()
    // store.dispatch('getAuthorityMenuList')
    //   .then(res => {
    //     console.log("111111111",res);
        
    //     if (res.code == 1) {
    //       router.addRoutes(res.resultRoutes)
    //       next({
    //         ...to, replace: true
    //       }) 
    //     } else {
    //       console.log("sssss44444444444");
    //       // store.dispatch('LogOut')
    //       // .then(() => {
    //       //   next({
    //       //     name: LOGIN_PAGE_NAME
    //       //   })
    //       // })
    //     }       
    //   })
 
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    next({
      name: 'welcome'
    })
  } else {
    const userInfo = store.state.user.userInfo
    // 用户信息不存在，先拉取用户信息, 然后依据用户权限表动态生成左侧菜单栏
    if (!userInfo) {
      store.dispatch('getUserInfo').then(res => {
        if (res.code === 1) {
          if (true) {
        //  if (store.state.user.userInfo.managerType) {
            const { roles } = store.getters

            let routes = getMenuByRouter(asyncRouterMap, roles)
            routes.sort(function (a, b) {
            return a - b
          })
            store.commit('ADD_MENUS', routes)
            router.addRoutes(routes)
            next({
              ...to, replace: true
            })
            // store.commit('ADD_MENUS', asyncRouterMap)
            // router.addRoutes(asyncRouterMap)
            // next({
            //   ...to, replace: true
            // })
          } else {
            store.dispatch('getAuthorityMenuList')
            .then(res => {
              console.log('res', res)
              if (res.code == 1) {
                router.addRoutes(res.resultRoutes)
                next({
                  ...to, replace: true
                }) 
              } else {
                store.dispatch('LogOut')
                .then(() => {
                  next({
                    name: LOGIN_PAGE_NAME
                  })
                })
              }       
            })
          }      
        } else {
          // 拉取用户信息业务码不等于1
          Notification({
            title: '警告',
            message: res.msg,
            type: 'error'
          })
          setTimeout(() => {
            console.log("sss222222");
            store.dispatch('LogOut')
            .then(() => {
              next({
                name: LOGIN_PAGE_NAME
              })
            })
          }, 2000);
        }
      })
      .catch(err => {
        console.log("sss111111");
        store.dispatch('LogOut')
        .then(() => {
          next({
            name: LOGIN_PAGE_NAME
          })
        })
      })
    } else {
      next()
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})

export default router